package com.graduation.cdm.funactivity.view.mineview;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.graduation.cdm.funactivity.MyApplication;
import com.graduation.cdm.funactivity.R;
import com.graduation.cdm.funactivity.bean.CollectBaen;
import com.graduation.cdm.funactivity.util.CommonAdapter;
import com.graduation.cdm.funactivity.util.GlobalConstant;
import com.graduation.cdm.funactivity.util.ViewHolder;
import com.graduation.cdm.funactivity.util.xUtilsImageUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.graduation.cdm.funactivity.util.DateUtils.longTosmallstring;
import static com.graduation.cdm.funactivity.util.GlobalConstant.preUrl;

public class CollectActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_love_back;
    private PullToRefreshListView lv_collect;

    Integer userId;
    Integer pageNow =1;
    Integer activityId;

    List<CollectBaen.Collect> collects = new ArrayList<>();
    CommonAdapter<CollectBaen.Collect> collectCommonAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect);

        initView();
        getData();

    }

    private void initView(){
        iv_love_back = ((ImageView) findViewById(R.id.iv_love_back));
        lv_collect = ((PullToRefreshListView) findViewById(R.id.lv_collect));
        iv_love_back.setOnClickListener(this);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        userId = sharedPreferences.getInt("userId",0);

        lv_collect.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        lv_collect.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(CollectActivity.this);
                builder.setMessage("是否要删除此收藏？");
                builder.setTitle("提示");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        activityId = collects.get(position-1).activityId;
                        SharedPreferences sharedPreferences = getSharedPreferences("collectId", Context.MODE_PRIVATE);
                        String collectId = sharedPreferences.getString("collectId", "");
                        String[] collect = collectId.split(",");
                        String collectId_new = "";
                        for (String string : collect) {
                            if (!string.equals(activityId+"")) {
                                collectId_new += string + ",";
                            }
                        }
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.putString("collectId", collectId_new);
                        editor.commit();//提交修改
                        cancelCollect();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
        lv_collect.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                pageNow++;
                getData();
            }
        });
    }

    private void getData(){
        String url = GlobalConstant.preUrl+"collect/findCollectById";
        StringRequest collectRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson = new Gson();
                CollectBaen collectBaen = gson.fromJson(s,CollectBaen.class);
                Integer pageCount = collectBaen.pageSum;
                if (pageNow == 1) {
                    collects.clear();
                }
                if (pageNow <= pageCount) {
                    collects.addAll(collectBaen.collectionList);
                }else {
                    Toast.makeText(getApplicationContext(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
                }
                initData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("userId",userId+"");
                map.put("pageNow",pageNow+"");
                map.put("pageSize",5+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(collectRequest);
    }

    private void initData(){
        if (collectCommonAdapter == null){
            collectCommonAdapter = new CommonAdapter<CollectBaen.Collect>(getApplicationContext(),collects,R.layout.collect_item) {
                @Override
                public void convert(ViewHolder viewHolder, CollectBaen.Collect collect, int position) {
                    TextView tv_createtime = viewHolder.getViewById(R.id.tv_createtime);
                    TextView tv_label = viewHolder.getViewById(R.id.tv_label);
                    TextView tv_theme = viewHolder.getViewById(R.id.tv_theme);
                    ImageView iv_photo = viewHolder.getViewById(R.id.iv_photo);

                    tv_createtime.setText(longTosmallstring(collect.collecTime));
                    tv_label.setText(collect.activityLable);
                    tv_theme.setText(collect.activityTitle);
                    xUtilsImageUtils.displayHome(iv_photo,preUrl+collect.activityImgurl);
                }
            };
            lv_collect.setAdapter(collectCommonAdapter);
        }else {
            collectCommonAdapter.notifyDataSetChanged();
        }
        lv_collect.onRefreshComplete();
    }

    private void cancelCollect() {
        String url = preUrl+"collect/deleteCollect";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("collect/deleteCollect=="+s.trim());
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.get("result").toString().equals("true")){
                        Toast.makeText(getApplicationContext(),"取消收藏！",Toast.LENGTH_SHORT).show();
                        pageNow =1 ;
                        getData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("activityId",activityId+"");
                map.put("userId",userId+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_love_back:
                finish();
                break;
        }
    }
}
